<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏房间</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_room.css">
    <script src="js/jquery.min.js"></script>
    <script src="js/app.js"></script>
</head>
<body>
    <div class="nav">五子棋对战</div>
    <div class="container">
        <div>
            <canvas id="chess" width="450px" height="450px"></canvas>
            <div id="screen">等待玩家连接中...</div>
        </div>
    </div>

    <script>
        let gameInfo = {
            roomId: null,
            thisUserId: null,
            thatUserId: null,
            isWhite: true,
        }


        function setScreenText(me) {
            let screen = document.querySelector('#screen');
            if (me) {
                screen.innerHTML = "轮到你落子了!";
            } else {
                screen.innerHTML = "轮到对方落子了!";
            }
        }


// 初始化 websocket

        let webSocketUrl = 'ws://' + location.host + '/game';
        let webSocket = new WebSocket(webSocketUrl);
        webSocket.onopen = function(){
            console.log("连接游戏房间成功");
        }
        webSocket.onclose = function(){
            console.log("和服务器连接断开");
        }

        webSocket.onerror = function(){
            console.log("和服务器连接出现异常");
        }
        window.onbeforeunload = function(){
            webSocket.onclose();
        }
//处理服务器返回的响应数据
        webSocket.onmessage = function(event){
            console.log("[handlerGame] " + event.data);
            let resp = JSON.parse(event.data);

            if(!resp.ok){
                alert("连接游戏失，reason" + resp.reason);
                location.replace("/game_hall.html");
                return;
            }
            if(resp.message == 'gameReady' ){
                gameInfo.roomId = resp.roomId;
                gameInfo.thisUserId = resp.thisUserId;
                gameInfo.thatUserId = resp.thatUserId;
                gameInfo.isWhite = (resp.whiteUser == resp.thisUserId);

                initGame();

                setScreenText(gameInfo.isWhite);
                return;
            }else  if(resp.message == 'repeatConnection'){
                console.log("检测到游戏多开");
                location.replace("/login.html");
                return;
            }

    
        }
//////////////////////////////////////////////////
// 初始化一局游戏
//////////////////////////////////////////////////
        function initGame() {
            // 是我下还是对方下. 根据服务器分配的先后手情况决定
            let me = gameInfo.isWhite;
            // 游戏是否结束
            let over = false;
            let chessBoard = [];
            //初始化chessBord数组(表示棋盘的数组)
            for (let i = 0; i < 15; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < 15; j++) {
                    chessBoard[i][j] = 0;
                }
            }
            let chess = document.querySelector('#chess');
            let context = chess.getContext('2d');
            context.strokeStyle = "#BFBFBF";
    // 背景图片
            let logo = new Image();
            logo.src = "img/sky.jpeg";
            logo.onload = function () {
                context.drawImage(logo, 0, 0, 450, 450);
                initChessBoard();
            }

    // 绘制棋盘网格
            function initChessBoard() {
                for (let i = 0; i < 15; i++) {
                    context.moveTo(15 + i * 30, 15);
                    context.lineTo(15 + i * 30, 430);
                    context.stroke();
                    context.moveTo(15, 15 + i * 30);
                    context.lineTo(435, 15 + i * 30);
                    context.stroke();
                }
            }

    // 绘制一个棋子, me 为 true
            function oneStep(i, j, isWhite) {
                context.beginPath();
                context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
                context.closePath();
                var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
                if (!isWhite) {
                    gradient.addColorStop(0, "#0A0A0A");
                    gradient.addColorStop(1, "#636766");
                } else {
                    gradient.addColorStop(0, "#D1D1D1");
                    gradient.addColorStop(1, "#F9F9F9");
                }
                context.fillStyle = gradient;
                context.fill();
            }

            chess.onclick = function (e) {
                if (over) {
                    return;
                }
                if (!me) {
                    return;
                }
                let x = e.offsetX;
                let y = e.offsetY;
                // 注意, 横坐标是列, 纵坐标是行
                let col = Math.floor(x / 30);
                let row = Math.floor(y / 30);
                if (chessBoard[row][col] == 0) {
            // TODO 发送坐标给服务器, 服务器要返回结果
                    send(row,col);
                    /* oneStep(col, row, gameInfo.isWhite);
                    chessBoard[row][col] = 1; */
                }
            }

            function send(row,col){
                let req = {
                    message:'putChess',
                    userId:gameInfo.thisUserId,
                    row:row,
                    col:col
                };
                webSocket.send(JSON.stringify(req));
            }

            webSocket.onmessage = function(event) {
                console.log("[handlerPutChess]" + event.data);
                let resp = JSON.parse(event.data);
                if(resp.message != 'putChess'){
                    console.log("响应错误");
                    return;
                }
                //判断这个棋子是哪个玩家落的
                if (resp.userId == gameInfo.thisUserId) {
                    oneStep(resp.col,resp.row,gameInfo.isWhite);
                }else if (resp.userId == gameInfo.thatUserId){
                    oneStep(resp.col,resp.row,!gameInfo.isWhite);
                }else{
                    console.log("[hanlerPutChess] resp userId 错误");
                    return;
                }

                chessBoard[resp.row][resp.col] = 1;

                me = !me;
                setScreenText(me);
                let screenDiv = document.querySelector('#screen');
                //判断游戏是否结束
                if(resp.winner != 0){
                    if(resp.winner == gameInfo.thisUserId){
                        screenDiv.innerHTML = '你赢了';

                    }else if(resp.winner == gameInfo.thatUserId){
                        screenDiv.innerHTML = '你输了';
                    }else{
                        alert("winner 字段错误");
                    }

                    let backBtn = document.createElement('button');
                    backBtn.innerHTML = '回到大厅';
                    backBtn.onclick = function(){
                        location.replace('/game_hall.html');
                    }
                    let fDiv = document.querySelector('.container>div');
                    fDiv.appendChild(backBtn);
                }
            }
            
        }


    </script>
</body>
</html>